package com.retail.bbq.cola.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.retail.bbq.cola.constant.ColaHttpUrlConfig;
import com.retail.bbq.cola.entity.WechatCustomer;
import com.retail.bbq.cola.enums.DeleteStatusEnum;
import com.retail.bbq.cola.enums.ErrorCodeEnum;
import com.retail.bbq.cola.exception.BusinessException;
import com.retail.bbq.cola.service.CouponService;
import com.retail.bbq.cola.service.PlatformTenantClientService;
import com.retail.bbq.cola.service.WechatCustomerService;
import com.retail.bbq.cola.vo.request.CouponRequest;
import com.retail.bbq.cola.vo.request.QuerMemberProjectListRequestVo;
import com.retail.bbq.cola.vo.response.MemberProjectListResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class CouponServiceImpl implements CouponService {

    @Value("${api.client.buCode}")
    private String buCode;
    @Value("${api.client.coupon.projectId}")
    private String couponProjectId;
    @Resource
    private ColaHttpUrlConfig colaHttpUrlConfig;
    @Resource
    private WechatCustomerService wechatCustomerService;
    @Resource
    private PlatformTenantClientService platformTenantClientService;

    /**
     * 判断用户是否已领券
     *
     * @param request
     * @return true 已到账 false 未领取券
     */
    @Override
    public Boolean customerReceiveJudge(CouponRequest request) {
        try {
            if (Objects.isNull(request) || Objects.isNull(request.getOneid())) {
                log.info("权益查询用户没有oneId:{}", request);
                return Boolean.FALSE;
            }
            WechatCustomer wechatCustomer = wechatCustomerService.getBaseMapper()
                    .selectOne(new LambdaQueryWrapper<WechatCustomer>()
                            .eq(WechatCustomer::getOneid, request.getOneid())
                            .eq(WechatCustomer::getIsDel, DeleteStatusEnum.no_del.getCode())
                            .last(" order by id asc limit 1"));
            if (Objects.isNull(wechatCustomer) || Objects.isNull(wechatCustomer.getThirdCustomerId())) {
                log.info("权益查询用户没有会员id:{}", wechatCustomer);
                return Boolean.FALSE;
            }
            QuerMemberProjectListRequestVo querMemberProjectListRequestVo = new QuerMemberProjectListRequestVo(wechatCustomer.getThirdCustomerId(), couponProjectId);
            //2.发请求
            String querMemberProjectListUrl = colaHttpUrlConfig.querMemberProjectListUrl(buCode);
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", platformTenantClientService.getAccessToken());
            // 4. 发送POST请求
            HttpResponse response = HttpRequest.post(querMemberProjectListUrl)
                    .headerMap(headers, true) // 添加Headers
                    .body(JSONUtil.toJsonStr(querMemberProjectListRequestVo)) // JSON参数
                    .execute();
            MemberProjectListResponse result = JSONObject.parseObject(response.body(), MemberProjectListResponse.class);
            if (result.getSuccess()) {
                log.info("权益查询成功:{}", result);
                if (ObjectUtil.isNotEmpty(request) && CollectionUtil.isNotEmpty(result.getData())) {
                    return Boolean.TRUE;
                }
            } else {
                log.error("查询权益失败:{}", result);
                throw new BusinessException(ErrorCodeEnum.POST_FAIL);
            }
        } catch (Exception e) {
            log.error("权益查询异常:请求入参:{}", request, e);
        }
        return Boolean.FALSE;
    }
}
